#include "coin.h"

Coin::Coin(QPushButton *parent) : QPushButton(parent)
{
    timer = new QTimer(this);
    defaultImage = "";
}

Coin::Coin(QString img)
{
    timer = new QTimer(this);
    if (useImage(img))
        defaultImage = img;

    connect(timer, &QTimer::timeout, this, [=]() {
        QPixmap pic;
        QString path;
        if (!flag) // 由于flag在changeFlag中已经改变了，因此这里相反
            path = QString(":/image/res/Coin000%1.png").arg(min++);
        else
            path = QString(":/image/res/Coin000%1.png").arg(max--);

        pic.load(path);
        this->setFixedSize(pic.width(), pic.height());
        this->setStyleSheet("QPushButton{border:0px;}");
        this->setIcon(pic);
        this->setIconSize(QSize(pic.width(), pic.height()));
        if (!flag && (min > max)) {
            min = 1;
            isAnimation = false;
            timer->stop();
        } else if (flag && (max < min)) {
            max = 8;
            isAnimation = false;
            timer->stop();
        }
    });
}

bool Coin::useImage(QString img)
{
    // 显示给定图片
    QPixmap pic;

    if (!pic.load(img)) {
        qDebug() << img << "图片加载失败";
        return false;
    }

    this->setFixedSize(pic.width(), pic.height());
    // 设置不规则图片的样式
    this->setStyleSheet("QPushButton{border:0px;}");
    this->setIcon(pic);
    this->setIconSize(QSize(pic.width(), pic.height()));
    return true;
}

void Coin::changeFlag()
{
    if (flag) {
        timer->start(30);
        isAnimation = true;
        flag = false;
    } else {
        timer->start(30);
        isAnimation = true;
        flag = true;
    }
}

void Coin::mousePressEvent(QMouseEvent *e)
{
    if (isAnimation || !Flipable)
        return;
    else
        return QPushButton::mousePressEvent(e);
}
